<template>
    <Headtop></Headtop>
    <Headmenu></Headmenu>
    
    <div id="main">
        <!-- 设置企业归属 -->
        <div class="other-box" v-if="verify">
            <div class="w100 flex-column-center pd20">
                <span class="title mt20 mb20">您还未选择企业归属，请在下方选择企业所属管委会及所在园区</span>
                <div class="form-box mt20 mb20">
                    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm">
                        <el-form-item :rules="[ { required: true, message: '请选择所属管委会'} ]" label="所属管委会" prop="management_id">
                            <el-select v-model="form.management_id" placeholder="请选择所属管委会" clearable @change="namachange">
                                <el-option v-for="item in manalist" :key="item.management_id" :label="item.name" :value="item.management_id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :rules="[ { required: true, message: '请选择所属园区'} ]" label="所属园区" prop="garden_id">
                            <el-select v-model="form.garden_id" placeholder="请选择所属园区" clearable>
                                <el-option v-for="item in gardenlist" :key="item.garden_id" :label="item.name" :value="item.garden_id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :rules="[ { required: true, message: '请选择所属街道'} ]" label="所属街道" prop="citys">
                            <el-cascader v-model="form.citys" :options="hebeicitys" placeholder="请选择所属街道" :props="{checkStrictly:true}" class="search_select w350px" clearable @change="(e)=>{form.city = e?e[e.length-1]:''}"/>
                        </el-form-item>
                        <el-form-item label=" " label-width="120px">
                            <el-button type="primary" class="btn" :loading="false" @click.prevent="submit" native-type="submit">提交</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
        <!-- 左侧导航菜单 -->
        <div class="left" v-if="!verify">
            <div class="item" :class="{'hid':m.showhid}" v-for="(m,i) in menu" :key="i">
                <span :class="[`icon ${m.icon}`,'pointer']" :icon-before="m.content" @click="m.showhid=!m.showhid">{{m.label}}</span>
                <a @click="toMenu(m,n)" :class="[`t${n.selected?'1':'0'}`,`${n.component}_`,'pointer']" v-for="n in m.sub" :key="n">{{n.label}}</a>
            </div>
        </div>
        <!-- 右侧内容 -->
        <div class="right" v-if="!verify">
            <el-breadcrumb separator="/" class="mb10" v-if="breadcrumbs&&breadcrumbs.length>0">
                <el-breadcrumb-item v-for="(v,i) in breadcrumbs" :key="i"><span class="pointer" @click="breadcrumb(v)">{{v.label}}</span></el-breadcrumb-item>
            </el-breadcrumb>
            <div class="router-view pb10">
                <router-view v-slot="{ Component }">
                    <keep-alive>
                        <component :is="Component" v-if="$route.meta.keepAlive" :key="$route.path"/>
                    </keep-alive>
                    <component :is="Component" v-if="!$route.meta.keepAlive"/>
                </router-view>
            </div>

        </div>
    </div>
    <Footer></Footer>

    <div class="suspension-box spot" :class="[obj.new?'spot1':'']">
        <div class="suspension flex-center  size32 write-color pointer" @click="obj.showtab=!obj.showtab;">
            <span class="mb5 icon"></span>
        </div>
        <div class="tab-box flex-column base-bg" v-show="obj.showtab">
            <div class="pd10 flex-center mini-size pointer active tab" v-for="(v,k) in obj.charts" :key="k" @click="chart(k)">
                <div :class="[v.isnew?'spot':'']">{{v.title}}</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive,ref,getCurrentInstance,toRefs,toRaw,watch,onBeforeUpdate } from 'vue'
import Stomp from "stompjs"
import Headtop from './components/headtop.vue'
import Headmenu from './components/headmenu.vue'
import Footer from './components/footer.vue'
let { proxy } = getCurrentInstance()


let cururl = proxy.$route.path.split('/',2)[1]; //这个是当前路由proxy.$route，上面上路由列表router.currentRoute.value，两个不一样
let obj = reactive({
    verify: false,
    manalist: [],
    gardenlist: [],
    ruleFormRef: null,
    form: {
        "garden_id":"",
        "management_id":"",
        city: '',
        citys: []
    },
    menu:[],
    submenu:[],
    breadcrumbs: [],
    myname:"",
    key:"",
    icons: {
        staff: "\e6c8",recruit: '\e609',property: '\e6c0',news: '\e6ca',my: '\e6bd',public: '\e6cb'
    },
    stompClient: null,

    charts: {
        persion: { title: '人才',isnew: false},
        train: { title: '培训',isnew: false},
        insurance: { title: '保险',isnew: false},
        banking: {title: '金融',isnew: false},
    },
    new: false,
    monitordata: proxy.$Websocket.monitordata
});

onBeforeUpdate(()=>{
    // console.log(proxy.$route);
    // 面包屑
    let val = proxy.$route.path.split(/\//g)[1]
    if(val=='main'){
        breadcrumbs.value = []
        return
    }
    let arr = findParents(menu.value,val,'')||[]
    breadcrumbs.value = arr.length>0?arr.concat([{label:'首页',url:'main'}]).reverse():[]
})
// const router = proxy.$router;
// watch(
//     ()=> router.currentRoute.value.path,(value)=>{
//         let val = value.split(/\//g)[1]
//         let arr = findParents(menu.value,val,'')||[]
//         breadcrumbs.value = arr.length>0?arr.concat([{label:'首页'}]).reverse():[]
//     }
// )
//找到所有父节点
const findParents = (treeData,val,label)=>{
  if(treeData.length==0) return
  for(let i=0;i<treeData.length;i++){
    if((treeData[i].component == val&&treeData[i].url.indexOf(val)!=-1)||treeData[i].label==label){
      return [treeData[i]]
    }else{
      if(treeData[i].sub){
        let res = findParents(treeData[i].sub,val,treeData[i].label)
        if(res !== undefined){
          return res.concat(treeData[i])
        }
      }
    }
  }  
}

watch(
    ()=>obj.charts,
    (o)=>{
        console.log(o);
        let nw = false;
        for (const key in o) {
            if (Object.hasOwnProperty.call(o, key)) {
                nw = o[key].isnew?true:nw
            }
        }
        obj.new = nw
    },{ deep: true }
)

watch(
    ()=>obj.monitordata,
    (msg)=>{
        console.log(msg);
        let v = proxy.globalData.topicObj[msg.type]
        if(msg.type==='talk'){//人才聊天
            obj.charts.persion.isnew = true;
        }else if(msg.type==='talk_banking'||msg.type==='talk_train'||msg.type==='talk_insurance'){//机构聊天
            // 直接提示跳转好像不对 每次有新消息都提示 out 
            // const notify = proxy.$notify({
            //     type: v.type||'success',
            //     position: 'bottom-right',
            //     duration: 0,
            //     title: v.title||'有新的消息通知',
            //     message: `${msg.title||''} 去看看 >>`,
            //     onClick: res=>{
            //         chart(msg.type.split('_')[1]);
            //         notify.close()
            //     }
            // })
                //换这种 有新消息加红点
            obj.charts[msg.type.split('_')[1]].isnew = true;
        }else{
            const notify = proxy.$notify({
                type: v.type||'success',
                position: 'bottom-right',
                duration: 0,
                title: v.title||'有新的消息通知',
                message: `${msg.title||''} 去看看 >>`,
                onClick: res=>{
                    goUrl(v.url,v.params)
                    notify.close()
                }
            })
        }
    },{ deep: true }
)

let chart = (type)=>{
    proxy.$ajax({url: type==='persion'?`talk/list`:`/talk/${type}/list`,data:{currentpage:1,pagesize:1},bfLoading: true}).then(d => {
        if(d.success&&d.msg.list.length){
            obj.charts[type].isnew = false;
            let o = d.msg.list[0]
            if(type==='persion'){
                proxy.routerPushNewMixin('/chartpersiondetail',{
                    job_id:o.job_id,
                    persion_id:o.persion_id,
                    persionname:o.persionname
                })
            }else{
                proxy.routerPushNewMixin('/chartmechanismdetail',{
                    id: o[`${type}_id`],
                    name: o[`${type}name`],
                    mechanism_id: o.mechanism_id,
                    mechanism_name: o.mechanismname,
                    type: type
                })              
            }
        }else{
            proxy.elMessageMixin(type==='persion'?'暂无人才咨询信息！':'暂无机构聊天信息！', 'error')
        }
    }).catch(e => {
        if(e == "登录已过期，请重新登录"){
            proxy.routerPushMixin('/')
        }
    })
}


const connectSocket = ()=>{
    proxy.$Websocket.init().then((e)=>{
        let title1 = `/topic/company/${sessionStorage.getItem("ID")}`;
        let title2 = `/topic/company/all`;
        proxy.$Websocket.addSubscribe(title1);
        proxy.$Websocket.addSubscribe(title2);
    })
}
connectSocket()


// 获取企业归属get
const getcompany = ()=>{
    proxy.$ajax({url: 'get',data: {},bfLoading: true}).then(d => {
        if(d.success){
            verify.value = d.msg.verify;
        }else{}
    }).catch(e => {
        if(e == "登录已过期，请重新登录"){
            proxy.routerPushMixin('/')
        }
    })
}
getcompany()
// 获取管委会
proxy.$utils.getManagement(proxy).then(res=>{
    manalist.value = res;
})
// 获取园区
const namachange = ()=>{
    proxy.$utils.getGarden(proxy,form.value.management_id).then(res=>{
        gardenlist.value = res;
    })
}

proxy.$ajax({
    url: 'menu',
    // url: 'getMenu',
    data: {},
    bfLoading: true
}).then(d => {
    // d.msg.authority.forEach(m => {
    d.msg.forEach(m => {
        m.showhid = !m.sub.some((v,i) => v.component == cururl) //返回bool，有一个满足即true
        if(!m.showhid){
            let ms = m.sub.filter(e => e.show);
            ms.forEach(e => e.selected = e.component == cururl)
            submenu.value = ms
        }
        m.sub = m.sub.filter(e => e.show && e.label);
        m.show = m.sub.some(t => t.label) //这是用来判断，子项若没有，本项不显示
        m.content = obj.icons[m.icon];
    })
    // menu.value = d.msg.authority.filter(t => t.show)
    // myname.value = d.msg.name
    menu.value = d.msg.filter(t => t.show)
}).catch(e => {
    if(e == "登录已过期，请重新登录")
        proxy.routerPushMixin('/')
})
let toMenu = (m,n,url) => {
    menu.value.forEach(ev=>{
        ev.show = ev.icon==m.con;
        ev.sub.forEach(e => e.selected = e.component == n.component)
    })
    submenu.value = m.sub?m.sub.filter(e => e.show):m
    proxy.routerPushMixin(url||n.component)
}

let breadcrumb = (v)=>{
    if(v.label=='首页'){
        toMenu({},{},'main')
    }
}

let goUrl = (url) =>{
    menu.value.forEach(ev=>{
        let showhid = true
        ev.sub.forEach(e => {
            e.selected = e.component == url
            if(showhid){
                showhid = !(e.component == url)
            }
        })
        ev.showhid = showhid
    })
    proxy.routerPushMixin(url)
}

const submit = ()=>{
    if (ruleFormRef) {
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            let param = {
                ...form.value,
            }
            // return
            proxy.$ajax({url: 'set',data:param,bfLoading: true}).then(d => {
                if(d.success){
                    proxy.elMessageMixin('设置成功！', 'success')
                    verify.value = false
                }else{proxy.elMessageMixin(date.err, 'error')}
            }).catch(e => {
                if(e == "登录已过期，请重新登录"){
                    proxy.routerPushMixin('/')
                }
            })
        } else {
        return false;
        }
    });
    }
}
//导出到页面
let { menu, submenu, breadcrumbs, myname, verify, form, ruleFormRef, manalist, gardenlist } = toRefs(obj)
</script>

<style lang="scss" scoped>
.suspension-box{
    position: fixed;right: 50px;bottom: 200px;z-index: 1;
    .suspension{
        position: relative;z-index: 1;
        width: 50px;height: 50px;border-radius: 50px;   background: #3586f4;
        .icon::before{ font-family: iconfont; content: '\e771';}
    }
    .tab-box{
        position: absolute;z-index: 0;left: 0;top: 0;width: 50px; padding: 50px 0 10px; border-radius: 50px; background: #fff; border: solid 1px #E0ECFF; box-sizing: border-box; overflow: hidden;
        .tab{position: relative;}
        .spot::after{
            content: '';width: 6px;height: 6px;position: absolute;z-index: 10; right: 6px;top: 10px;border-radius: 6px; background: #ff3300;
        }
    }
    .active:hover{color: #3586f4;}
}
.spot1::after{
    content: '';width: 8px;height: 8px;position: absolute;z-index: 10; right: 4px;top: 4px;border-radius: 8px; background: #ff3300;
}
#main {
    max-width: 1200px; min-width: 1200px; width: 100%; box-sizing: border-box; display:flex; margin:0 auto; padding:16px 0;
    .other-box{
        width: 1148px;font-size: 16px; border: 1px solid #f0f0f0; box-sizing: border-box;
        .title{color: #999;}
        .form-box{

        }
    }
    .left {
        width: 237px; font-size: 16px; border: 1px solid #f0f0f0; box-sizing: border-box; margin: 0 8px;
        
        .item {
            color: #333333;
            * { clear: both; display: block; }
            &:first-child::before { height: 0; }
            &:hover { color: #096dd9; }
            span { 
                font-size: 16px; height: 72px; line-height: 72px;
                &::after { font-family: iconfont; content: '\e74c'; display: block; float: right; color: #9f9f9f; margin-right: 16px; font-size: 12px; }
                &:hover::after,&:hover::before { color: #096dd9; }
                &::before { font-family: iconfont; color: #9f9f9f; margin-right: 16px; margin-left: 24px; }
            }
            .staff::before{content: '\e6c8';}
            .recruit::before{content: '\e6c9';}
            .property::before{content: '\e6c0';}
            .news::before{content: '\e6ca';}
            .my::before{content: '\e6bd';}
            .public::before{content: '\e6cb';}
            .visitor::before{content: '\e6c8';}
            a {
                font-size: 16px; height: 50px; line-height: 50px; cursor: pointer; background-color: #fafafa;
                // &.t1 { color: #FFFFFF; background-color: #2B8DEF; }
                &.t1 { border-radius: 6px; background:#096dd9!important; box-shadow: 0 6px 8px 0 rgb(0 106 241 / 36%); color: #fff; margin: 0 -10px;}
                // &.t1:before { content:"\e630"; font-family:iconfont; margin: 0 10px 0 24px; font-size:20px; }
                &::before {content: '\e64e';font-family: iconfont; padding-left:48px; padding-right:12px; font-size: 14px;}
            }
             .staff_::before{content: '\e64e';}.recruit_::before{content: '\e623';}.persion_::before{content: '\e63c';}
             .applyfor_::before{content: '\e62e';}.interview_::before{content: '\e659';}.parking_::before{content: '\f712';}
             .repair_::before{content: '\e65e';}.life_::before{content: '\e8a9';}.news_::before{content: '\e771';}
             .persion_::before{content: '\e64e';}.activity_::before{content: '\e64d';}.train_::before{content: '\e78c';}
             .finance_::before{content: '\e688';}.banking_::before{content: '\e688';}.financialpolicy_::before{content: '\e64b';}
             .insurance_::before{content: '\e895';}
            
            &.hid {
                a { display: none; }
                span::after { content: '\e665'; }
            }
        }
    }
    .right {
        width: 930px; height: auto;font-size: 16px; margin: 0 8px;
        .router-view{
            width: 930px;border: 1px solid #f0f0f0; box-sizing: border-box;
        }
    }
}
// #main #submenu { position: relative; left: 20px; top: 20px; right: 0; height: 37px; border-bottom: 1px solid #DDD; }
// #main #submenu span { display: none; }
// #main #submenu::after { content: ''; display: block; clear: both; }
// #main #submenu a { padding:8px 16px; font-size: 14px; color: #333; display: block; float: left; border:1px solid #DDD; margin-left: -1px; }
// #main #submenu a.selected { border-bottom: 1px solid #FFF; background-color: #FFF; border-top: 2px solid #3a4fbd;}
// #main #subbody { position: absolute; left: 20px; right: 20px; bottom: 0px; top: 70px; }
// #main #subbody > div { width: 100%; height: 100%; }

</style>